package util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Properties;

public class ClientInfoManager {

    public final static int DEFAULT_PORT = 43;
    public final static String DEFAULT_HOST = "whois.ripe.net";
    String query;
    Socket socket;
    InputStream in, fin;
    OutputStream out;
    Properties prop;

    public ClientInfoManager()  {

     
    }

    public synchronized ClientInfo putQuery(String query) throws Exception {

        InetAddress server = InetAddress.getByName(DEFAULT_HOST);
        socket = new Socket(server, DEFAULT_PORT);
        in = socket.getInputStream();
        out = socket.getOutputStream();
        ClientInfo clientInfoObj = new ClientInfo();
        query += "\n";
        try {
            out.write(query.getBytes());
            out.flush();
        } catch (Exception e) {
            System.out.println("Exception while writing client ip query "+e);
        }
        String res = null;
        byte data[];
        int cnt = 0;
        while (cnt++ < 4) {

            Thread.sleep(500);

            if (in.available() > 0) {

                int size = in.available();
                data = new byte[size];

                in.read(data, 0, size);

                for (int i = 0; i < size; i++) {
                    res += (char) data[i];
                }

                prop = new Properties();

                fin = new ByteArrayInputStream(res.getBytes());
                prop.load(fin);

                if (prop.containsKey("netname")) {
                    clientInfoObj.ISP = prop.getProperty("netname");
                }
                if (prop.containsKey("country")) {
                    clientInfoObj.Country = prop.getProperty("country");
                }
                break;

            }

        }
        in.close();
        out.close();
        socket.close();
        return clientInfoObj;
    }
}
